<template>
  <view class="file-upload">
    <!-- 上传按钮 -->
    <button 
      class="upload-btn"
      :class="{ 'upload-btn--disabled': disabled || isUploading }"
      @click="handleClickUpload"
      :disabled="disabled || isUploading"
    >
      <uni-icons type="cloud-upload" size="16" color="#fff"></uni-icons>
      <text>{{ uploadText }}</text>
    </button>

    <!-- 已上传文件列表 -->
    <view class="file-list" v-if="completedFiles.length > 0">
      <text class="list-title">已上传文件 ({{ completedFiles.length }})</text>
      <view 
        v-for="(file, index) in completedFiles" 
        :key="file.id" 
        class="file-item"
      >
        <text class="file-name">{{ file.name }}</text>
        <view class="file-actions">
          <view class="file-status">
            <!-- 空的状态区域，保持布局一致 -->
          </view>
          <view class="action-buttons">
            <button class="remove-btn" @click="removeCompletedFile(index)">
              <uni-icons type="close" size="16" color="#f56c6c"></uni-icons>
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 上传中的文件列表 -->
    <view class="uploading-list" v-if="uploadQueue.length > 0">
      <text class="list-title">上传中 ({{ uploadQueue.length }})</text>
      <view 
        v-for="(file, index) in uploadQueue" 
        :key="file.id" 
        class="file-item"
        :class="{ 'file-item--error': file.status === 'error' }"
      >
        <text class="file-name">{{ file.name }}</text>
        <view class="file-actions">
          <view class="file-status">
            <view v-if="file.status === 'waiting'" class="status-text">等待中</view>
            <view v-else-if="file.status === 'uploading'" class="status-text">{{ Math.round(file.progress) }}%</view>
            <view v-else-if="file.status === 'completed'" class="status-text success">完成</view>
            <view v-else-if="file.status === 'error'" class="status-text error">失败</view>
          </view>
          <view class="action-buttons">
            <button class="remove-btn" @click="removeFile(index)">
              <uni-icons type="close" size="16" color="#f56c6c"></uni-icons>
            </button>
            <button 
              v-if="file.status === 'waiting' && !isUploading" 
              class="upload-btn-small" 
              @click="startSingleUpload(file)"
            >
              <uni-icons type="upload" size="16" color="#fff"></uni-icons>
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { createUploadManager, formatFileSize, generateFileId } from '@/utils/upload-utils'

export default {
  name: 'FileUpload',
  props: {
    // v-model 值，支持字符串（逗号分隔）和数组
    modelValue: {
      type: [String, Array],
      default: () => []
    },
    // 最大文件数量
    limit: {
      type: Number,
      default: 5
    },
    // 单个文件最大大小(MB)
    maxFileSize: {
      type: Number,
      default: 1024
    },
    // 允许的文件类型
    allowedTypes: {
      type: Array,
      default: () => ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'zip', 'rar']
    },
    // 默认存储配置ID
    defaultConfigId: {
      type: Number,
      default: null
    },
    // 默认上传目录
    defaultDir: {
      type: String,
      default: ''
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 分片大小(MB)
    chunkSize: {
      type: Number,
      default: 5
    },
    // 是否显示存储配置选择
    showConfig: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'upload-success', 'upload-error', 'upload-progress'],
  data() {
    return {
      isDragActive: false,
      isUploading: false,
      uploadQueue: [],
      completedFiles: [],
      storageConfigs: [],
      selectedConfigId: this.defaultConfigId,
      selectedConfigIndex: 0,
      uploadDir: this.defaultDir,
      // 动态文件大小限制（来自存储配置）
      dynamicMaxFileSize: this.maxFileSize,
      // 上传管理器
      uploadManager: null
    }
  },
  computed: {
    uploadText() {
      if (this.disabled) return '上传已禁用'
      if (this.isUploading) return '上传中...'
      return '上传文件'
    },
    storageConfigNames() {
      return this.storageConfigs.map(config => config.configName)
    },
    selectedConfigName() {
      if (this.selectedConfigIndex >= 0 && this.storageConfigs[this.selectedConfigIndex]) {
        return this.storageConfigs[this.selectedConfigIndex].configName
      }
      return ''
    }
  },
  watch: {
    defaultConfigId(newVal) {
      if (newVal && newVal !== this.selectedConfigId) {
        this.selectedConfigId = newVal
        this.updateDynamicMaxFileSize()
      }
    },
    defaultDir(newVal) {
      this.uploadDir = newVal
    },
    selectedConfigId() {
      this.updateDynamicMaxFileSize()
    },
    modelValue: {
      handler() {
        if (!this.isInternalUpdate) {
          this.initFromModelValue()
        }
      },
      deep: true
    },
    completedFiles: {
      handler() {
        this.isInternalUpdate = true
        this.updateModelValue()
        this.$nextTick(() => {
          this.isInternalUpdate = false
        })
      },
      deep: true
    }
  },
  created() {
    this.isInternalUpdate = false
    this.initUploadManager()
    this.initFromModelValue()
  },
  mounted() {
    // 总是尝试加载存储配置，确保组件可以正常工作
    this.loadStorageConfigs()
  },
  methods: {
    formatFileSize,
    
    // 初始化上传管理器
    initUploadManager() {
      this.uploadManager = createUploadManager({
        allowedTypes: this.allowedTypes,
        maxFileSize: this.dynamicMaxFileSize,
        maxCount: this.limit,
        chunkSize: this.chunkSize,
        currentCount: () => this.completedFiles.length,
        queueCount: () => this.uploadQueue.length,
        disabled: () => this.disabled,
        isUploading: () => this.isUploading,
        canAddMore: () => this.uploadQueue.length < this.limit
      })
    },

    // 点击上传区域
    handleClickUpload() {
      if (this.disabled || this.isUploading) return
      
      // 确保在用户激活的事件中立即调用文件选择器
      this.chooseFiles()
    },

    // 选择文件
    chooseFiles() {
      try {
        // 获取系统信息，检测运行环境
        const systemInfo = uni.getSystemInfoSync()
        const platform = systemInfo.platform
        
        // 根据不同平台使用不同的文件选择API
        if (platform === 'devtools' || uni.getAccountInfoSync?.()?.miniProgram) {
          // 微信小程序环境
          this.chooseFilesForMiniProgram()
        } else {
          // H5或其他环境
          this.chooseFilesForOther()
        }
      } catch (error) {
        console.error('文件选择失败:', error)
        uni.showToast({
          title: '文件选择器调用失败',
          icon: 'none'
        })
      }
    },

    // 微信小程序文件选择
    chooseFilesForMiniProgram() {
      const count = this.limit - this.uploadQueue.length
      
      // 显示文件选择选项
      uni.showActionSheet({
        itemList: ['从聊天记录选择', '拍照', '从相册选择图片'],
        success: (res) => {
          switch(res.tapIndex) {
            case 0:
              // 从聊天记录选择文件
              this.chooseMessageFiles(count)
              break
            case 1:
              // 拍照
              this.chooseImageFromCamera(count)
              break
            case 2:
              // 从相册选择
              this.chooseImageFromAlbum(count)
              break
          }
        },
        fail: (err) => {
          console.log('用户取消选择')
        }
      })
    },

    // 从聊天记录选择文件
    chooseMessageFiles(count) {
      uni.chooseMessageFile({
        count: count,
        type: 'all',
        success: (res) => {
          console.log('小程序文件选择成功:', res)
          if (res.tempFiles && res.tempFiles.length > 0) {
            // 转换文件格式以适配组件
            const files = res.tempFiles.map((file, index) => {
              // 确保文件名存在，如果不存在则生成一个
              const fileName = file.name || file.path || `file_${Date.now()}_${index}.bin`
              const fileType = file.type || this.getFileTypeFromName(fileName)
              
              return {
                name: fileName,
                path: file.path,
                tempFilePath: file.path,
                size: file.size,
                type: fileType
              }
            })
            this.addFilesToQueue(files)
          }
        },
        fail: (err) => {
          console.error('小程序文件选择失败:', err)
          uni.showToast({
            title: '选择文件失败',
            icon: 'none'
          })
        }
      })
    },

    // 拍照选择
    chooseImageFromCamera(count) {
      uni.chooseImage({
        count: Math.min(count, 1), // 拍照一次只能一张
        sourceType: ['camera'],
        success: (res) => {
          console.log('拍照成功:', res)
          if (res.tempFilePaths && res.tempFilePaths.length > 0) {
            const files = res.tempFilePaths.map((path, index) => ({
              name: `photo_${Date.now()}_${index}.jpg`,
              path: path,
              tempFilePath: path,
              size: res.tempFiles?.[index]?.size || 0,
              type: 'image/jpeg'
            }))
            this.addFilesToQueue(files)
          }
        },
        fail: (err) => {
          console.error('拍照失败:', err)
          uni.showToast({
            title: '拍照失败',
            icon: 'none'
          })
        }
      })
    },

    // 从相册选择图片
    chooseImageFromAlbum(count) {
      uni.chooseImage({
        count: count,
        sourceType: ['album'],
        success: (res) => {
          console.log('相册选择成功:', res)
          if (res.tempFilePaths && res.tempFilePaths.length > 0) {
            const files = res.tempFilePaths.map((path, index) => ({
              name: `image_${Date.now()}_${index}.jpg`,
              path: path,
              tempFilePath: path,
              size: res.tempFiles?.[index]?.size || 0,
              type: 'image/jpeg'
            }))
            this.addFilesToQueue(files)
          }
        },
        fail: (err) => {
          console.error('相册选择失败:', err)
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },

    // 其他环境文件选择
    chooseFilesForOther() {
      const count = this.limit - this.uploadQueue.length
      
      // 尝试使用chooseFile API
      if (typeof uni.chooseFile === 'function') {
        uni.chooseFile({
          count: count,
          type: 'all',
          success: (res) => {
            console.log('文件选择成功:', res)
            if (res.tempFiles && res.tempFiles.length > 0) {
              this.addFilesToQueue(res.tempFiles)
            }
          },
          fail: (err) => {
            console.error('文件选择失败:', err)
            uni.showToast({
              title: '选择文件失败',
              icon: 'none'
            })
          }
        })
      } else {
        // 降级到H5文件选择
        this.chooseFilesForH5()
      }
    },

    // H5环境文件选择
    chooseFilesForH5() {
      // 创建隐藏的input元素
      const input = document.createElement('input')
      input.type = 'file'
      input.multiple = this.limit > 1
      input.accept = this.getAcceptString()
      
      input.onchange = (event) => {
        const files = Array.from(event.target.files || [])
        if (files.length > 0) {
          // 转换为uni-app格式
          const uniFiles = files.map(file => ({
            name: file.name,
            path: URL.createObjectURL(file),
            tempFilePath: URL.createObjectURL(file),
            size: file.size,
            type: file.type,
            file: file // 保留原始文件对象
          }))
          this.addFilesToQueue(uniFiles)
        }
      }
      
      input.click()
    },

    // 根据文件名推断文件类型
    getFileTypeFromName(fileName) {
      // 确保fileName是字符串类型且不为空
      if (!fileName || typeof fileName !== 'string') {
        return 'application/octet-stream'
      }
      
      try {
        // 转换为字符串并获取扩展名
        const fileNameStr = String(fileName)
        const parts = fileNameStr.toLowerCase().split('.')
        const ext = parts.length > 1 ? parts.pop() : ''
        
        const typeMap = {
          'jpg': 'image/jpeg',
          'jpeg': 'image/jpeg',
          'png': 'image/png',
          'gif': 'image/gif',
          'pdf': 'application/pdf',
          'doc': 'application/msword',
          'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'xls': 'application/vnd.ms-excel',
          'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'ppt': 'application/vnd.ms-powerpoint',
          'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
          'txt': 'text/plain',
          'zip': 'application/zip',
          'rar': 'application/x-rar-compressed'
        }
        
        return typeMap[ext] || 'application/octet-stream'
      } catch (error) {
        console.error('获取文件类型失败:', error, '文件名:', fileName)
        return 'application/octet-stream'
      }
    },

    // 获取H5 accept属性字符串
    getAcceptString() {
      const typeMap = {
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'png': 'image/png',
        'gif': 'image/gif',
        'pdf': 'application/pdf',
        'doc': 'application/msword',
        'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'txt': 'text/plain'
      }
      
      const mimeTypes = this.allowedTypes.map(type => typeMap[type]).filter(Boolean)
      const extensions = this.allowedTypes.map(type => `.${type}`)
      
      return [...mimeTypes, ...extensions].join(',')
    },

    // 存储配置选择变化
    handleConfigChange(e) {
      const index = e.detail.value
      this.selectedConfigIndex = index
      if (this.storageConfigs[index]) {
        this.selectedConfigId = this.storageConfigs[index].configId
      }
    },

    // 添加文件到队列
    addFilesToQueue(files) {
      if (!this.uploadManager) {
        this.initUploadManager()
      }

      const { validFiles, errors } = this.uploadManager.validator.validateFiles(files, this.uploadQueue)

      // 显示错误信息
      errors.forEach(error => {
        uni.showToast({
          title: error,
          icon: 'error',
          duration: 3000
        })
      })

      // 处理有效文件
      const processedFiles = validFiles.map(file => ({
        id: generateFileId(),
        file: file,
        name: file.name,
        size: file.size,
        type: file.type || this.getFileTypeFromName(file.name),
        status: 'waiting',
        progress: 0,
        uploadMethod: this.uploadManager.determineUploadMethod(file),
        supportDirectUpload: false,
        errorMessage: '',
        filePath: '',
        uploadId: '',
        etags: []
      }))

      this.uploadQueue.push(...processedFiles)
    },


    // 移除文件
    removeFile(index) {
      this.uploadQueue.splice(index, 1)
    },

    // 开始单个文件上传
    async startSingleUpload(fileObj) {
      // 确保有存储配置
      if (!this.selectedConfigId) {
        if (this.storageConfigs.length > 0) {
          this.selectedConfigId = await this.getDefaultConfigId(this.storageConfigs)
        } else {
          await this.loadStorageConfigs()
          if (this.storageConfigs.length === 0) {
            uni.showToast({
              title: '没有可用的存储配置',
              icon: 'error'
            })
            return
          }
          this.selectedConfigId = await this.getDefaultConfigId(this.storageConfigs)
        }
      }

      try {
        const config = this.storageConfigs.find(c => c.configId === this.selectedConfigId)
        if (!config) {
          throw new Error('未找到存储配置信息')
        }

        fileObj.status = 'uploading'
        fileObj.progress = 0
        fileObj.errorMessage = ''

        if (fileObj.uploadMethod === 'chunk') {
          await this.uploadFileWithChunks(fileObj, config)
        } else {
          await this.uploadFileNormally(fileObj, config)
        }

        fileObj.status = 'completed'
        fileObj.progress = 100

        // 移动到已完成列表
        this.completedFiles.push({
          id: fileObj.id,
          name: fileObj.name,
          filePath: fileObj.filePath,
          url: fileObj.url,
          size: fileObj.size
        })

        // 从队列中移除
        const index = this.uploadQueue.findIndex(f => f.id === fileObj.id)
        if (index > -1) {
          this.uploadQueue.splice(index, 1)
        }

        this.$emit('upload-success', {
          file: fileObj,
          filePath: fileObj.filePath
        })

        uni.showToast({
          title: '上传成功',
          icon: 'success'
        })

      } catch (error) {
        fileObj.status = 'error'
        fileObj.errorMessage = error.message || '上传失败'

        this.$emit('upload-error', {
          file: fileObj,
          error: error
        })

        uni.showToast({
          title: '上传失败：' + error.message,
          icon: 'error'
        })
      }
    },

    // 开始上传
    async startUpload() {
      // 确保有存储配置
      if (!this.selectedConfigId) {
        if (this.storageConfigs.length > 0) {
          this.selectedConfigId = await this.getDefaultConfigId(this.storageConfigs)
        } else {
          // 尝试重新加载配置
          await this.loadStorageConfigs()
          if (this.storageConfigs.length === 0) {
            uni.showToast({
              title: '没有可用的存储配置',
              icon: 'error'
            })
            return
          }
          this.selectedConfigId = await this.getDefaultConfigId(this.storageConfigs)
        }
      }

      if (this.uploadQueue.length === 0) {
        uni.showToast({
          title: '没有文件需要上传',
          icon: 'none'
        })
        return
      }

      this.isUploading = true
      uni.showLoading({
        title: '上传中...'
      })

      try {
        // 获取存储配置信息
        const config = this.storageConfigs.find(c => c.configId === this.selectedConfigId)
        
        if (!config) {
          throw new Error('未找到存储配置信息')
        }

        // 逐个上传文件
        for (const fileObj of this.uploadQueue) {
          if (fileObj.status === 'completed') continue

          try {
            fileObj.status = 'uploading'
            fileObj.progress = 0
            fileObj.errorMessage = ''

            if (fileObj.uploadMethod === 'chunk') {
              await this.uploadFileWithChunks(fileObj, config)
            } else {
              await this.uploadFileNormally(fileObj, config)
            }

            fileObj.status = 'completed'
            fileObj.progress = 100

            // 移动到已完成列表
            this.completedFiles.push({
              id: fileObj.id,
              name: fileObj.name,
              filePath: fileObj.filePath,
              url: fileObj.url,
              size: fileObj.size
            })

            this.$emit('upload-success', {
              file: fileObj,
              filePath: fileObj.filePath
            })

          } catch (error) {
            fileObj.status = 'error'
            fileObj.errorMessage = error.message || '上传失败'

            this.$emit('upload-error', {
              file: fileObj,
              error: error
            })
          }
        }

        uni.showToast({
          title: '上传完成',
          icon: 'success'
        })

      } catch (error) {
        uni.showToast({
          title: '上传过程中发生错误：' + error.message,
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
        this.isUploading = false
      }
    },

    // 普通上传
    async uploadFileNormally(fileObj, config) {
      const onProgress = (progress) => {
        this.$emit('upload-progress', { file: fileObj, progress })
      }

      await this.uploadManager.uploadFileNormally(
        fileObj, config, this.selectedConfigId, this.uploadDir, onProgress
      )
    },

    // 分片上传
    async uploadFileWithChunks(fileObj, config) {
      const onProgress = (progress) => {
        this.$emit('upload-progress', { file: fileObj, progress })
      }

      await this.uploadManager.uploadFileWithChunks(
        fileObj, config, this.selectedConfigId, this.uploadDir, this.chunkSize, onProgress
      )
    },

    // 取消上传
    async cancelUpload() {
      try {
        const res = await new Promise((resolve) => {
          uni.showModal({
            title: '提示',
            content: '确定要取消上传吗？',
            success: resolve
          })
        })

        if (!res.confirm) return

        // 取消所有正在进行的分片上传
        for (const fileObj of this.uploadQueue) {
          if (fileObj.status === 'uploading' && fileObj.uploadId) {
            try {
              await this.uploadManager.abortMultipartUpload(
                fileObj.filePath, fileObj.uploadId, this.selectedConfigId
              )
            } catch (error) {
              // 取消分片上传失败，忽略错误
            }
          }
          if (fileObj.status === 'uploading') {
            fileObj.status = 'waiting'
            fileObj.progress = 0
          }
        }

        this.isUploading = false
        uni.showToast({
          title: '已取消上传',
          icon: 'none'
        })

      } catch (error) {
        // 用户取消确认
      }
    },

    // 重试上传
    retryUpload(fileObj) {
      fileObj.status = 'waiting'
      fileObj.progress = 0
      fileObj.errorMessage = ''
    },

    // 清空结果
    clearResults() {
      this.completedFiles = []
      this.uploadQueue = this.uploadQueue.filter(file => file.status !== 'completed')
    },

    // 移除已完成的文件
    removeCompletedFile(index) {
      this.completedFiles.splice(index, 1)
    },

    // 复制路径
    copyPath(path) {
      this.uploadManager.copyPath(path)
    },

    // 复制文件URL
    async copyFileUrl(file) {
      try {
        let url = ''

        // 检查是否已有完整URL
        if (file.url && file.url.startsWith('http')) {
          url = file.url
        } else if (file.filePath) {
          // 通过API获取完整URL
          url = await this.uploadManager.getImageUrl(file.filePath, this.selectedConfigId)
        } else if (file.url) {
          // file.url 可能是相对路径，通过API获取完整URL
          url = await this.uploadManager.getImageUrl(file.url, this.selectedConfigId)
        }

        if (url) {
          uni.setClipboardData({
            data: url,
            success: () => {
              uni.showToast({
                title: '文件URL已复制到剪贴板',
                icon: 'success'
              })
            }
          })
        } else {
          uni.showToast({
            title: '文件URL为空',
            icon: 'error'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '复制文件URL失败: ' + error.message,
          icon: 'error'
        })
      }
    },

    // 加载存储配置
    async loadStorageConfigs() {
      try {
        this.storageConfigs = await this.uploadManager.loadStorageConfigs()

        if (this.storageConfigs && this.storageConfigs.length > 0) {
          if (!this.selectedConfigId) {
            this.selectedConfigId = await this.getDefaultConfigId(this.storageConfigs)
            this.selectedConfigIndex = this.storageConfigs.findIndex(
              config => config.configId === this.selectedConfigId
            )
          }

          // 更新动态文件大小限制
          this.updateDynamicMaxFileSize()
        } else {
          uni.showToast({
            title: '没有可用的存储配置',
            icon: 'error'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '加载存储配置失败',
          icon: 'error'
        })
      }
    },

    // 获取默认配置ID
    async getDefaultConfigId(configs) {
      if (!configs || configs.length === 0) {
        return null
      }
      
      // 优先使用默认配置
      const defaultConfig = configs.find(config => config.isDefault === 1)
      if (defaultConfig) {
        return defaultConfig.configId
      }
      
      // 如果没有默认配置，使用第一个可用配置
      return configs[0].configId
    },

    // 更新动态文件大小限制
    updateDynamicMaxFileSize() {
      if (this.selectedConfigId && this.storageConfigs.length > 0) {
        const config = this.storageConfigs.find(c => c.configId === this.selectedConfigId)
        if (config && config.maxFileSize) {
          // 将字节转换为MB
          this.dynamicMaxFileSize = Math.floor(config.maxFileSize / (1024 * 1024))
        }
      }
      // 重新初始化上传管理器以使用新的文件大小限制
      this.initUploadManager()
    },

    // v-model 相关函数
    initFromModelValue() {
      if (!this.modelValue) {
        this.completedFiles = []
        return
      }

      let files = []
      if (typeof this.modelValue === 'string') {
        files = this.modelValue.split(',').filter(path => path.trim())
      } else if (Array.isArray(this.modelValue)) {
        files = this.modelValue
      }

      this.completedFiles = files.map((filePath, index) => {
        const fileName = this.getFileNameFromPath(filePath)
        return {
          id: `existing_${index}`,
          name: fileName,
          filePath: filePath,
          size: 0 // 已存在的文件无法获取大小
        }
      })
    },

    updateModelValue() {
      const filePaths = this.completedFiles
        .filter(file => file.filePath)
        .map(file => file.filePath)

      if (typeof this.modelValue === 'string') {
        this.$emit('update:modelValue', filePaths.join(','))
      } else {
        this.$emit('update:modelValue', filePaths)
      }
    },

    getFileNameFromPath(filePath) {
      if (!filePath) return ''
      const parts = filePath.split('/')
      return parts[parts.length - 1]
    }
  }
}
</script>

<style lang="scss" scoped>
.file-upload {
  .upload-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    width: 200rpx;
    height: 64rpx;
    background: #409eff;
    color: #fff;
    border: none;
    border-radius: 8rpx;
    font-size: 28rpx;
    transition: all 0.3s ease;

    &:active:not(.upload-btn--disabled) {
      background: #337ecc;
      transform: scale(0.98);
    }

    &--disabled {
      background: #c0c4cc;
      opacity: 0.6;
    }
  }

  .file-list,
  .uploading-list {
    margin-top: 24rpx;
    width: 100%;
    box-sizing: border-box;

    .list-title {
      font-size: 28rpx;
      color: #606266;
      font-weight: 500;
      margin-bottom: 16rpx;
      display: block;
    }

    .file-item {
      padding: 16rpx 20rpx;
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 8rpx;
      margin-bottom: 12rpx;

      &:last-child {
        margin-bottom: 0;
      }

      &--error {
        background: #fef0f0;
        border-color: #fbc4c4;
      }

      .file-name {
        display: block;
        font-size: 28rpx;
        color: #303133;
        margin-bottom: 12rpx;
        word-break: break-all;
        line-height: 1.4;
      }

      .file-actions {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .file-status {
          display: flex;
          align-items: center;

          .status-text {
            font-size: 24rpx;
            color: #909399;

            &.success {
              color: #67c23a;
            }

            &.error {
              color: #f56c6c;
            }
          }
        }

        .action-buttons {
          display: flex;
          align-items: center;
          gap: 12rpx;
        }

        .remove-btn {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 48rpx;
          height: 48rpx;
          min-width: 48rpx;
          min-height: 48rpx;
          background: rgba(245, 108, 108, 0.1);
          border: 1rpx solid rgba(245, 108, 108, 0.3);
          border-radius: 24rpx;
          transition: all 0.2s ease;
          padding: 0;
          box-sizing: border-box;
          flex-shrink: 0;

          &:active {
            background: rgba(245, 108, 108, 0.2);
            transform: scale(0.95);
          }
        }

        .upload-btn-small {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 48rpx;
          height: 48rpx;
          min-width: 48rpx;
          min-height: 48rpx;
          background: #409eff;
          border: none;
          border-radius: 24rpx;
          transition: all 0.2s ease;
          padding: 0;
          box-sizing: border-box;
          flex-shrink: 0;

          &:active {
            background: #337ecc;
            transform: scale(0.95);
          }
        }
      }
    }

  }
}
</style>
